//
//  YZMFastPayViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/5.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMFastPayViewController.h"
#import "YZMHintInputView.h"
#import "YZMBankModel.h"
#import "UIViewController+Utils.h"
#import "YZClient.h"
#import "NSNumber+Utils.h"
#import "MBProgressHUD+Utils.h"
#import "NSString+Utils.h"
#import "JSONBaseDeal.h"
#import "YZMWebViewService.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import "Zhugeio/Zhuge.h"

#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;

#define payLianlian @"pay_lianlian"
#define payLiandong @"pay_liandong"
#define payAiBei    @"pay_iapppay"
#define payZFB   @"pay_zhifubao"
#define payHeFuBao  @"pay_hfbpay"

@interface YZMFastPayViewController()

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *balanceLB;
@property (nonatomic, strong) YZMHintInputView *amountInputView;
@property (nonatomic, strong) UIButton *submitBT;
@property (nonatomic, assign) BOOL backFlag;
@property (nonatomic, strong) NSString *billNO;
@property (nonatomic, assign) BOOL confirmFlag;
@property (nonatomic, strong) UILabel *limitLB;
@property (nonatomic, strong) NSDictionary *param;

@end

@interface YZMFastPayViewController()<UITextFieldDelegate>

@end

@implementation YZMFastPayViewController

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.title = @"账户充值";
    [self createObjects];
    [self registerForKeyboardAutoWithBottomView:self.bottomView];
}

#pragma makr -- confirm

- (void)checkIfRechargeFinished{
    
    if (self.confirmFlag && self.billNO.length != 0) {
        
        self.confirmFlag = NO;
        [self fetchRechargeResult:self.billNO];
    }
}

#pragma mark -- event

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self checkIfRechargeFinished];
}

- (void)resignFirstResponderAll{
    
    [self.view endEditing:YES];
}

- (void)submitButtonPressed:(UIButton *)sender{
    
    [self resignFirstResponderAll];
    
    if (![@([self.amountInputView.textField.text doubleValue]) isEqualGreaterThanDouble:100.0]) {
        
        [MBProgressHUD showMessage:@"最低100元起充"];
        return;
    }
    if ([self.param[@"payMethod"] isEqualToString:payHeFuBao]) {
        if ([@([self.amountInputView.textField.text doubleValue]) isGreaterThanDouble:2000.0]) {
            
            [MBProgressHUD showMessage:@"单次充值最高2000元"];
            return;
        }
    }else{
        if ([@([self.amountInputView.textField.text doubleValue]) isGreaterThanDouble:5000.0]) {
            
            [MBProgressHUD showMessage:@"单次充值最高5000元"];
            return;
        }
    }
   
    
    [self fetchPayURLWithMoney:self.amountInputView.textField.text];
}

- (void)textValueChanged:(UITextField *)field{
    
    if ([field isEqual:self.amountInputView.textField]) {
        
        if ([field.text isEqualToString:@"."]) {
            
            /*第一位为.时，变更为0.*/
            field.text = @"0.";
        }
//        [self refreshChargeLB];
    }
    
    [self refreshSubmitButton];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([textField isEqual:self.amountInputView.textField]) {
        
        if (!string || string.length == 0) {
            
            return YES;
        }
        
        if ( [@([textField.text doubleValue]) isGreaterThanDouble:10000000]) {
            
            return NO;
        }
        
        if ([string isEqualToString:@"."]) {
            
            NSRange range = [textField.text rangeOfString:@"."];
            if (range.length != 0) {
                return FALSE;
            }
            
        }else{
            
            NSRange range = [textField.text rangeOfString:@"."];
            if( range.length != 0 && textField.text.length - range.location >2){
                
                return false;
            }
        }
    }
    
    return YES;
}


#pragma mark -- network

- (void)fetchRechargeResult:(NSString *)billNo{
    
    //获取支付结果
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"获取支付结果"];
    [YZClient rd_fetchRechargeResultWithBillNo:self.billNO success:^(NSURLResponse *response, id responseObject) {
        
        [hud hide:NO];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            BOOL rechargeResult = [JSONBaseDeal getBoolValue:@"success" fromData:topModel.data];
            if (rechargeResult) {
                
#ifndef DEBUG_MODE
                
                NSMutableDictionary *properties = [NSMutableDictionary dictionary];
                properties[@"充值金额"] = self.amountInputView.textField.text;
                [[Zhuge sharedInstance] track:@"充值" properties:properties];
#endif
                
                YZMUserServiceInstance.user.assets.balance = [JSONBaseDeal getDoubleValue:@"balance" fromData:topModel.data];
                //判断是否需要返回点买页面
                if (self.backFlag) {
                    
                    [YZMHCMInstance popViewControllerBeforeControllerName:@"recharge" animated:YES];
                    
                }else{
                    //交易成功
                    [YZMHCMInstance pushAfterRootWithName:@"fundDetail" andParams:@{@"fundType":@(YZS_FUND_TYPE_FOR_RECHARGE)} atIndex:self.tabBarController.selectedIndex];
                }
            }
        }else{
            
            [YZMUserServiceInstance fetchUserAssetsInfo];
        }
        
    } failure:^(NSError *error) {
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (void)fetchPayURLWithMoney:(NSString *)money{
    
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"请求获取中"];
    WS(ws);
    [YZClient rd_fetchRechargeURLWithMoney:money payMethod:ws.param[@"payMethod"]  success:^(NSURLResponse *task, id responseObject) {
        
        [hud hide:NO];
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            NSString *urlString = topModel.data;
//            NSDictionary *dic  = [NSJSONSerialization JSONObjectWithData:[urlString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dic = topModel.data;
//            NSString *strUrl = [dic objectForKey:@"url"];
            
//            self.billNO = [self fetchBillNoFromString:strUrl];
//            self.billNO = [self fetchBillNoFromString:urlString];
            
            self.confirmFlag = YES;
            if (ws.param != nil || [ws.param.allKeys containsObject:@"payMethod"]) {
                if ([ws.param[@"payMethod"] isEqualToString:payLiandong] ||[ws.param[@"payMethod"] isEqualToString:payAiBei]) {
                    [YZMWebViewService openFastConfirmViewWithString:urlString];
                }else if ([ws.param[@"payMethod"] isEqualToString:payHeFuBao]){
                    [YZMWebViewService openFastConfirmViewWithDic:dic];
                }
            }

        }else{
            
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (NSString *)fetchBillNoFromString:(NSString *)string{
    
    NSRange range = [[string lowercaseString] rangeOfString:@"billno"];
    NSString *beginString = [string substringFromIndex:range.location];
    NSRange subRange = [beginString rangeOfString:@"&"];
    NSString *endString = [beginString substringToIndex:subRange.location];
    
    NSArray *array = [endString componentsSeparatedByString:@"="];
    
    if (array.count < 2) {
        
        return nil;
    }
    
    return array[1];
}

- (void)fetchUserAssetsWithBalance:(double)balance andBlock:(void (^)())block{
    
    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"充值成功，更新余额中"];
    [YZMUserServiceInstance fetchUserAssetsSuccess:^{
        
        [hud hide:NO];
        if (block) {
            
            block();
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        YZMUserServiceInstance.user.assets.balance += balance;
        if (block) {
            block();
        }
    }];
}



#pragma mark -- ui

- (void)createObjects{
    
    WS(ws)
    
    _bottomView = [UIView new];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.bottom.equalTo(self.view);
        maker.height.mas_equalTo(0);
    }];
    
    UIScrollView *bgSV = [UIScrollView new];
    bgSV.backgroundColor = [UIColor clearColor];
    bgSV.showsVerticalScrollIndicator = NO;
    [self.view addSubview:bgSV];
    [bgSV mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.top.right.equalTo(ws.view);
        maker.bottom.equalTo(_bottomView.mas_top);
    }];
    
    UIView *containerView = [UIView new];
    containerView.backgroundColor = [UIColor clearColor];
    [bgSV addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.edges.equalTo(bgSV);
        maker.width.equalTo(bgSV);
    }];
    
    
    UIView *balanceView = [UIView new];
    balanceView.backgroundColor = [YZMAppStyle colorForMain];
    [containerView addSubview:balanceView];
    [balanceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(containerView);
        make.right.equalTo(containerView);
    }];
    
    UIView *lineView = [YZMAppStyle splitLine];
    [balanceView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(balanceView);
    }];
    
    self.balanceLB = [YZMAppStyle labelWithLargeWhite];
    self.balanceLB.text = [@"账户余额：" stringByAppendingFormat:@"%@元", @(YZMUserServiceInstance.user.assets.balance).decimalP02fString];
    [balanceView addSubview:self.balanceLB];
    [self.balanceLB mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.equalTo(balanceView).offset(20);
        maker.left.equalTo(balanceView).offset(15);
        maker.bottom.equalTo(balanceView).offset(-20);
    }];
    
    UIImageView *logoIV = [UIImageView new];
    logoIV.image = [UIImage imageNamed:@"icon_recharge_fastpay"];
    [containerView addSubview:logoIV];
    [logoIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(balanceView.mas_bottom).offset(15);
        make.left.equalTo(containerView).offset(15);
        make.width.mas_equalTo(66);
        make.height.mas_equalTo(ceil(66 * 0.43));
    }];
    
    UILabel *fastpayLB = [YZMAppStyle labelWithMediumLightGray];
    fastpayLB.text = @"无需开通网银，有银行卡就能支付";
    [containerView addSubview:fastpayLB];
    [fastpayLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(logoIV);
        make.left.equalTo(logoIV.mas_right).offset(15);
    }];
    
//    UILabel *nameLB = [YZMAppStyle labelWithMediumGray];
//    nameLB.text = [@"持卡人姓名：" stringByAppendingString:[YZMUserServiceInstance.user.detail.name formatName]],
//    [containerView addSubview:nameLB];
//    [nameLB mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(logoIV.mas_bottom).offset(20);
//        make.left.equalTo(containerView).offset(15);
//    }];
//    
//    UIView *lastView = nil;
//    if (YZMUserServiceInstance.user.bankCard) {
//        
//        //已绑定银行卡
//        UIView *cardView = YZMUserServiceInstance.user.bankCard.bankCardView;
//        [containerView addSubview:cardView];
//        [cardView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(nameLB.mas_bottom).offset(15);
//            make.left.right.equalTo(containerView);
//            make.height.mas_equalTo(60);
//        }];
//        
//        lastView = cardView;
//        
//        
//    }else{
//        
//        //未绑定银行卡
//        self.chooseBankBT = [UIButton new];
//        self.chooseBankBT.layer.borderColor = [YZMAppStyle colorForLine].CGColor;
//        self.chooseBankBT.layer.borderWidth = 1;
//        [self.chooseBankBT setBackgroundColor:[UIColor whiteColor]];
//        [self.chooseBankBT setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
//        [self.chooseBankBT setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
//        [self.chooseBankBT setTitle:@"选择开户行" forState:UIControlStateNormal];
//        [self.chooseBankBT setTitleColor:[YZMAppStyle colorForGrayText] forState:UIControlStateNormal];
//        [self.chooseBankBT.titleLabel setFont:[YZMAppStyle largeSizeFont]];
//        
//        __weak __typeof(&*self) weakSelf = self;
//        [self.chooseBankBT bk_addEventHandler:^(id sender) {
//            [weakSelf resignFirstResponderAll];
//            [YZMHCMInstance pushViewControllerWithName:@"YZMBankListViewController" andParams:@{@"selectAction":^(YZMBankModel *bank){
//                
//                weakSelf.bank = bank;
//                [weakSelf.chooseBankBT setImage:weakSelf.bank.iconImage forState:UIControlStateNormal];
//                [weakSelf.chooseBankBT setTitle:weakSelf.bank.name forState:UIControlStateNormal];
//                [weakSelf.chooseBankBT setImageEdgeInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
//                [weakSelf.chooseBankBT setTitleEdgeInsets:UIEdgeInsetsMake(0, 25, 0, -25)];
//                [self refreshSubmitButton];
//                
//            }}];
//            
//        } forControlEvents:UIControlEventTouchUpInside];
//        [containerView addSubview:self.chooseBankBT];
//        [self.chooseBankBT mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(containerView).offset(-1);
//            make.right.equalTo(containerView).offset(1);
//            make.top.equalTo(nameLB.mas_bottom).offset(15);
//            make.height.mas_equalTo(60);
//        }];
//        
//        UIImageView *arrowIV = [UIImageView new];
//        arrowIV.image = [UIImage imageNamed:@"icon_gray_right_arrow"];
//        [self.chooseBankBT addSubview:arrowIV];
//        [arrowIV mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.right.equalTo(containerView).offset(-15);
//            make.centerY.equalTo(self.chooseBankBT);
//            make.height.width.mas_equalTo(12);
//        }];
//        
//        self.bankCardInputView = [YZMHintInputView new];
//        self.bankCardInputView.textField.delegate = self;
//        self.bankCardInputView.inputLabel.text = @"银行卡号";
//        self.bankCardInputView.textField.keyboardType = UIKeyboardTypeNumberPad;
//        self.bankCardInputView.textField.placeholder = @"请输入银行卡号";
//        [self.bankCardInputView.textField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
//        [containerView addSubview:self.bankCardInputView];
//        [self.bankCardInputView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.chooseBankBT.mas_bottom).offset(15);
//            make.left.right.equalTo(containerView);
//            make.height.mas_equalTo(44);
//        }];
//        
//        lastView = self.bankCardInputView;
//    }
    
    self.amountInputView = [YZMHintInputView new];
    self.amountInputView.inputLabel.text = @"充值金额";
    self.amountInputView.textField.delegate = self;
    self.amountInputView.textField.placeholder = @"最低100元起充";
    
    self.amountInputView.lineTopView.hidden=NO;
    self.amountInputView.lineBottomView.hidden=NO;
    
    self.amountInputView.textField.keyboardType = UIKeyboardTypeDecimalPad;
    [self.amountInputView.textField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [containerView addSubview:self.amountInputView];
    [self.amountInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logoIV.mas_bottom).offset(20);
        make.left.right.equalTo(containerView);
        make.height.mas_equalTo(44);
    }];
    
//    UILabel *feeStringLB = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForRedText]];
//    feeStringLB.text = @"充值手续费：";
//    [containerView addSubview:feeStringLB];
//    [feeStringLB mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(containerView).offset(15);
//        make.top.equalTo(self.amountInputView.mas_bottom).offset(15);
//        
//    }];
//    
//    self.feeLB = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForRedText]];
//    self.feeLB.text = @"0.00元";
//    [containerView addSubview:self.feeLB];
//    [self.feeLB mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(feeStringLB.mas_right);
//        make.centerY.equalTo(feeStringLB);
//    }];
//    
    self.limitLB = [YZMAppStyle labelWithSmallLightGray];
    if ([self.param[@"payMethod"] isEqualToString:payHeFuBao]) {
        self.limitLB.text = @"注：单卡单笔限额2000，每日最高1万，不支持信用卡";
    }else{
        self.limitLB.text = @"注：单卡单笔限额5000，每日最高1万，不支持信用卡";
    }
    [containerView addSubview:self.limitLB];
    [self.limitLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(containerView).offset(15);
        make.top.equalTo(self.amountInputView.mas_bottom).offset(10);
    }];
    
//    self.submitBT = [YZMAppStyle submitButton];
    self.submitBT = [YZMAppStyle NewsubmitButton];
    [self.submitBT setTitle:@"提交" forState:UIControlStateNormal];
    [self.submitBT addTarget:self action:@selector(submitButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:self.submitBT];
    [self.submitBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.limitLB.mas_bottom).offset(30);
        make.left.equalTo(containerView).offset(15);
        make.right.equalTo(containerView).offset(-15);
        make.bottom.equalTo(containerView).offset(-10);
    }];
    
}

#pragma mark -- refresh ui

//- (void)refreshChargeLB{
//    
//    self.charge = [@([self.amountInputView.textField.text doubleValue]*7.0/1000.0) convertChargeFee];
//    
//    if ( ![@(self.charge) isEqualWithDouble:0.0] && ![@(self.charge) isGreaterThanDouble:0.01]) {
//        self.charge = 0.01;
//    }
//    self.feeLB.text = [@(self.charge).p02fString stringByAppendingString:@"元"];
//}

- (void)refreshSubmitButton{
    
    if (self.amountInputView.textField.text.length == 0 ) {
        self.submitBT.layer.borderWidth=1.0;
        self.submitBT.enabled = NO;
        return;
    }
    
//    if (!YZMUserServiceInstance.user.bankCard) {
//        
//        if (!self.bank || self.bankCardInputView.textField.text.length == 0) {
//            self.submitBT.enabled = NO;
//            return;
//        }
//    }
    
    self.submitBT.enabled = YES;
    self.submitBT.layer.borderWidth=0.0;
}


#pragma mark - controller manager support

- (void)updateWithParams: (NSDictionary *)params
{
    self.backFlag = [params[YZBACKFLAG] boolValue];
    self.param = params;
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMFastPayViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

@end
